package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2024/10/10 8:55
 * @Version 1.0
 */
@Component
@Slf4j
@Aspect
public class AutoFillAspect {

    //定义切入点
    @Pointcut("execution(* com.sky.mapper..*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void pointCut(){

    }

    @Before("pointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始填充公共参数");
        //作甚？  就是填充参数（分两种情况 1.新增  2.修改）
        //解决问题，怎么知道他是新增或者修改
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        //获取操作类型
        OperationType operationType = autoFill.value();

        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        //获取参数
        Object[] args = joinPoint.getArgs();
        //防御性编程
        if(args == null || args.length == 0){
            return;
        }
        Object entity = args[0];
        try {
            //新增的时候需要填充4个字段，修改需2个字段
            if (operationType == OperationType.INSERT) {
                Method createUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method createTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method updateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                Method updateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);

                createUser.invoke(entity,currentId);
                createTime.invoke(entity,now);
                updateUser.invoke(entity,currentId);
                updateTime.invoke(entity,now);
            } else if (operationType == OperationType.UPDATE) {
                Method updateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                Method updateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                updateUser.invoke(entity,currentId);
                updateTime.invoke(entity,now);
            }
        }catch (Exception e){
            log.error("填充公共方法异常",e);
        }

    }
}